<?php
namespace Cmf\Plugins;

use Phalcon\Mvc\User\Plugin;

use Cmf\Models\Log;

/**
 * LogPlugin
 *
 * Handles log controller/action
 */
class LogPlugin extends Plugin
{
    private $flash;
    private $session;
    private $dispatcher;
    
    public function __construct()
    {
        $this->flash = $this->getDI()->getShared('flash');
        $this->session = $this->getDI()->getShared('session');
        $this->dispatcher = $this->getDI()->getShared('dispatcher');
    }
    
    public function afterCreate($event, $model)
    {
        if ($model->getSource() !== 'tm_log') {
            $user = $this->session->get('auth_identity');
            $action = $this->dispatcher->getActionName();
            $controller = $this->dispatcher->getControllerName();
            
            if ((Log::createLogRecord($user, $controller, $action, $model->getSource(), $model->id)) === false) {
                $this->flash->error('更新日志失败');
                
                return $this->dispatcher->forward(['controller' => $controller, 'action' => $action]);
            }
            
            return true;
        }
    }
    
    public function afterUpdate($event, $model)
    {
        $user = $this->session->get('auth_identity');
        $action = $this->dispatcher->getActionName();
        $controller = $this->dispatcher->getControllerName();
        
        if ((Log::createLogRecord($user, $controller, $action, $model->getSource(), $model->id)) === false) {
            $this->flash->error('更新日志失败');
            
            return $this->dispatcher->forward(['controller' => $controller, 'action' => $action]);
        }
        
        return true;
    }
}
